// lib/projectapi.ts
// 项目管理相关的 API 接口

import { apiClient, API_ENDPOINTS, TokenManager } from '@/lib/api-client'
import type { 
  Project, 
  CreateProjectRequest, 
  UpdateProjectRequest, 
  ProjectResponse, 
  ProjectListResponse,
  NewProjectForm
} from '@/types/project'

/**
 * 数据转换工具类
 */
export class ProjectDataTransformer {
  /**
   * 将表单数据转换为 API 请求格式
   */
  static formToRequest(formData: NewProjectForm): CreateProjectRequest | UpdateProjectRequest {
    // 确保 objectives是字符串类型
    let objectivesArray: string[] = []
    if (typeof formData.objectives === 'string' && formData.objectives.trim()) {
      objectivesArray = formData.objectives.split('\n').filter(obj => obj.trim())
    } else if (Array.isArray(formData.objectives)) {
      objectivesArray = formData.objectives.filter(obj => typeof obj === 'string' && obj.trim())
    }
    
    // 如果没有目标，提供默认值
    if (objectivesArray.length === 0) {
      objectivesArray = ['项目目标']
    }

    const requestData: any = {
      name: formData.name,
      description: formData.description || '项目描述',
      crop_type: formData.crop_type,
      location: formData.location,
      start_date: formData.start_date || undefined,
      end_date: formData.end_date || undefined,
      manager: formData.manager,
      budget: parseFloat(formData.budget) || 0,
      objectives: objectivesArray,
      attachments: formData.attachments || []
    }
    
    // 只有在编辑模式下且 status 存在且不为空时才包含 status 字段
    if (formData.status !== undefined && formData.status) {
      requestData.status = formData.status
    }
    
    return requestData
  }

  /**
   * 为包含附件的请求创建 FormData
   */
  static createFormData(data: CreateProjectRequest | UpdateProjectRequest, isUpdate = false): FormData {
    const formData = new FormData()
    
    // 添加项目基本信息
    Object.entries(data).forEach(([key, value]) => {
      if (key !== 'attachments' && value !== undefined) {
        if (key === 'objectives' && Array.isArray(value)) {
          // 确保 objectives 是有效的 JSON 数组，且不为空
          if (value.length === 0) {
            formData.append('objectives', JSON.stringify(['项目目标']))
          } else {
            formData.append('objectives', JSON.stringify(value))
          }
        } else {
          formData.append(key, value.toString())
        }
      }
    })
    
    // 添加附件
    if (data.attachments && data.attachments.length > 0) {
      const attachmentKey = isUpdate ? 'new_attachments' : 'attachments'
      data.attachments.forEach((file) => {
        formData.append(attachmentKey, file)
      })
    }
    
    return formData
  }
}

/**
 * 项目 API 类
 */
export class ProjectAPI {
  
  /**
   * 获取项目列表
   */
  static async getProjects(filters?: {
    status?: string
    crop_type?: string
    search?: string
  }): Promise<ProjectListResponse> {
    const queryParams = new URLSearchParams()
    
    if (filters?.status) {
      queryParams.append('status', filters.status)
    }
    if (filters?.crop_type) {
      queryParams.append('crop_type', filters.crop_type)
    }
    if (filters?.search) {
      queryParams.append('search', filters.search)
    }
    
    const endpoint = `${API_ENDPOINTS.projects}${queryParams.toString() ? `?${queryParams.toString()}` : ''}`
    return apiClient.get<ProjectListResponse>(endpoint)
  }

  /**
   * 根据 ID 获取项目详情
   */
  static async getProject(projectId: string): Promise<Project> {
    return apiClient.get<Project>(API_ENDPOINTS.projectDetail(projectId))
  }

  /**
   * 创建新项目
   */
  static async createProject(projectData: CreateProjectRequest): Promise<ProjectResponse> {
    // 处理附件上传
    if (projectData.attachments && projectData.attachments.length > 0) {
      const formData = ProjectDataTransformer.createFormData(projectData)
      return apiClient.post<ProjectResponse>(API_ENDPOINTS.projects, formData)
    } else {
      // 不包含附件的项目，直接传递请求数据
      const payload = { ...projectData }
      delete payload.attachments
      return apiClient.post<ProjectResponse>(API_ENDPOINTS.projects, payload)
    }
  }

  /**
   * 更新项目
   */
  static async updateProject(
    projectId: string, 
    projectData: UpdateProjectRequest
  ): Promise<ProjectResponse> {
    // 处理附件上传
    if (projectData.attachments && projectData.attachments.length > 0) {
      const formData = ProjectDataTransformer.createFormData(projectData, true)
      return apiClient.patch<ProjectResponse>(API_ENDPOINTS.projectDetail(projectId), formData)
    } else {
      // 确保所有数据都经过正确转换
      const payload = { ...projectData }
      // 移除 attachments 字段避免发送空数组
      delete payload.attachments
      return apiClient.patch<ProjectResponse>(API_ENDPOINTS.projectDetail(projectId), payload)
    }
  }

  /**
   * 删除项目
   */
  static async deleteProject(projectId: string): Promise<void> {
    return apiClient.delete<void>(API_ENDPOINTS.projectDetail(projectId))
  }

  /**
   * 上传项目附件
   */
  static async uploadAttachments(
    projectId: string, 
    files: File[]
  ): Promise<{ message: string; attachments: any[] }> {
    const formData = new FormData()
    
    files.forEach((file) => {
      formData.append('attachments', file)
    })
    
    return apiClient.post<{ message: string; attachments: any[] }>(
      API_ENDPOINTS.projectAttachments(projectId), 
      formData
    )
  }

  /**
   * 删除项目附件
   */
  static async deleteAttachment(
    projectId: string, 
    attachmentId: string
  ): Promise<void> {
    return apiClient.delete<void>(
      API_ENDPOINTS.attachmentDetail(projectId, attachmentId)
    )
  }

  /**
   * 下载项目附件
   */
  static async downloadAttachment(
    projectId: string, 
    attachmentId: string,
    fileName: string
  ): Promise<void> {
    try {
      const token = TokenManager.getAccessToken()
      // 直接构造 URL，不依赖内部属性
      const baseUrl = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:8000'
      const url = `${baseUrl}${API_ENDPOINTS.attachmentDownload(projectId, attachmentId)}`
      
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        throw new Error('下载失败')
      }
      
      const blob = await response.blob()
      const downloadUrl = window.URL.createObjectURL(blob)
      
      // 创建下载链接
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      // 清理 URL 对象
      window.URL.revokeObjectURL(downloadUrl)
    } catch (error: any) {
      console.error('下载附件失败:', error)
      throw error
    }
  }
}

export default ProjectAPI